package com.we.flink.userlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableOfflineLabel {
    public static final String KFKTABLE = "fdm.rrd03_offline_personas_label_v2";
    //    public static final String KFKTABLE = "fdm.rrd03_offline_personas_label_v2_risk";
    public static final String QUERYSQL =
            "select uid, user_key, "
                    + "if(his_max_overdue_days is null, -1, his_max_overdue_days) as his_max_overdue_days, "
                    + "if(his_max_overdue_principal is null, -1, his_max_overdue_principal) as his_max_overdue_principal, "
                    + "if(his_30_max_overdue_days is null, -1, his_30_max_overdue_days) as his_30_max_overdue_days, "
                    + "if(his_90_max_overdue_days is null, -1, his_90_max_overdue_days) as his_90_max_overdue_days"
                    + " from "
                    + KFKTABLE;

    public long uid;
    public String user_key;
    public int his_max_overdue_days;
    public float his_max_overdue_principal;
    public int his_30_max_overdue_days;
    public int his_90_max_overdue_days;

    public TableOfflineLabel() {}

    public TableOfflineLabel(
            long uid,
            String user_key,
            int his_max_overdue_days,
            float his_max_overdue_principal,
            int his_30_max_overdue_days,
            int his_90_max_overdue_days) {
        this.uid = uid;
        this.user_key = user_key;
        this.his_max_overdue_days = his_max_overdue_days;
        this.his_max_overdue_principal = his_max_overdue_principal;
        this.his_30_max_overdue_days = his_30_max_overdue_days;
        this.his_90_max_overdue_days = his_90_max_overdue_days;
    }

    public static TableOfflineLabel init(long uid) {
        return new TableOfflineLabel(uid, "", -1, -1f, -1, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableOfflineLabel.QUERYSQL);
        DataStream<Tuple2<Boolean, TableOfflineLabel>> inputStream =
                tableEnv.toRetractStream(tableRes, TableOfflineLabel.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableOfflineLabel>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableOfflineLabel> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagOfflineLabel-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableOfflineLabel>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableOfflineLabel> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableOfflineLabel>, String>() {
                                    ValueState<TableOfflineLabel> offlineLabelVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        offlineLabelVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableOfflineLabel>(
                                                                        "OfflineLabelVState",
                                                                        TableOfflineLabel.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableOfflineLabel> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        String user_key = value.f1.getUser_key();
                                        int his_30_max_overdue_days =
                                                value.f1.getHis_30_max_overdue_days();
                                        int his_90_max_overdue_days =
                                                value.f1.getHis_90_max_overdue_days();
                                        int his_max_overdue_days =
                                                value.f1.getHis_max_overdue_days();
                                        float his_max_overdue_principal =
                                                value.f1.getHis_max_overdue_principal();

                                        TableOfflineLabel tmpState = offlineLabelVState.value();
                                        TableOfflineLabel curState =
                                                (tmpState == null
                                                        ? TableOfflineLabel.init(uid)
                                                        : tmpState);

                                        if (!curState.getUser_key().equals(user_key)
                                                || curState.getHis_max_overdue_principal()
                                                        != his_max_overdue_principal
                                                || curState.getHis_max_overdue_days()
                                                        != his_max_overdue_days
                                                || curState.getHis_30_max_overdue_days()
                                                        != his_30_max_overdue_days
                                                || curState.getHis_90_max_overdue_days()
                                                        != his_90_max_overdue_days) {
                                            curState.user_key = user_key;
                                            curState.his_max_overdue_days = his_max_overdue_days;
                                            curState.his_max_overdue_principal =
                                                    his_max_overdue_principal;
                                            curState.his_30_max_overdue_days =
                                                    his_30_max_overdue_days;
                                            curState.his_90_max_overdue_days =
                                                    his_90_max_overdue_days;

                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("uid", uid);
                                            jsonObject.put("user_key", user_key);
                                            jsonObject.put(
                                                    "his_max_overdue_days",
                                                    (his_max_overdue_days == -1
                                                            ? null
                                                            : his_max_overdue_days));
                                            jsonObject.put(
                                                    "his_max_overdue_principal",
                                                    (his_max_overdue_principal == -1f
                                                            ? null
                                                            : his_max_overdue_principal));
                                            jsonObject.put(
                                                    "his_30_max_overdue_days",
                                                    (his_30_max_overdue_days == -1
                                                            ? null
                                                            : his_30_max_overdue_days));
                                            jsonObject.put(
                                                    "his_90_max_overdue_days",
                                                    (his_90_max_overdue_days == -1
                                                            ? null
                                                            : his_90_max_overdue_days));

                                            out.collect(jsonObject.toString());
                                            offlineLabelVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getUser_key() {
        return user_key;
    }

    public int getHis_max_overdue_days() {
        return his_max_overdue_days;
    }

    public float getHis_max_overdue_principal() {
        return his_max_overdue_principal;
    }

    public int getHis_30_max_overdue_days() {
        return his_30_max_overdue_days;
    }

    public int getHis_90_max_overdue_days() {
        return his_90_max_overdue_days;
    }
}
